﻿using Infrastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Implement
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly DBContext db;

        public BaseRepository(DBContext db)
        {
            this.db = db;
        }

        /// <summary>
        /// 添加(单)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> Add(T entity)
        {
            db.Set<T>().Add(entity);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 真删(单)
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public async Task<int> Del(T entitys)
        {
            db.Set<T>().Remove(entitys);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 修改(单)
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> Upd(T entity)
        {
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 查询(单)
        /// </summary>
        /// <returns></returns>
        public async Task<T> GetOne(int t)
        {
            return await db.Set<T>().FindAsync(t);
        }

        /// <summary>
        ///批量添加
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public async Task<int> AddRange(List<T> entitys)
        {
            db.Set<T>().AddRange(entitys);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 批量真删
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> DelRange(List<T> entity)
        {
            db.Set<T>().RemoveRange(entity);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 批量修改(批量逻辑删)
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public async Task<int> UpdRange(List<T> entitys)
        {
            db.Set<T>().UpdateRange(entitys);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<IQueryable<T>> GetAllAsync()
        {
            return db.Set<T>();
        }

        /// <summary>
        /// 同步查询
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return db.Set<T>();
        }

    }
}
